package ar.edu.uba.fi.jmit.monitorengine.backend.server;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import ar.edu.uba.fi.jmit.monitorengine.backend.client.StatisticsService;
import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.EventDTO;
import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.StatisticPair;
import ar.edu.uba.fi.jmit.monitorengine.core.EventServiceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class StatisticsServiceImpl extends RemoteServiceServlet implements StatisticsService {

	private static final long serialVersionUID = 3378233163710119824L;

	@Override
	public List<StatisticPair> getAllReceiverStatistics() {
		Logger.getLogger(this.getClass()).debug("getAllReceiverStatistics");
		List<StatisticPair> statistics = new LinkedList<StatisticPair>();
		statistics.add(new StatisticPair("Received Messages", String.valueOf(EventServiceManager.getInstance().getCountEventDTOs())));
		LinkedList<EventDTO> eventsDTOs = EventServiceManager.getInstance().getEventDTOs();
		if(eventsDTOs.size() == 0) {
			Logger.getLogger(this.getClass()).info("No Received events yet.");
			return new LinkedList<StatisticPair>();
		}
		long nowMiliSecs = System.currentTimeMillis();
		int index;
		int msg1Minute = 0;
		for (index = 0; index < eventsDTOs.size(); index++) {
			long diffMiliSecs = nowMiliSecs - eventsDTOs.get(index).getEventDate().getTime(); 
			if (diffMiliSecs <= 60000)//60 seconds
				msg1Minute++;
			else
				break;
		}
		int msg10Minutes = msg1Minute;
		for (; index < eventsDTOs.size(); index++) {
			long diffMiliSecs = (nowMiliSecs - eventsDTOs.get(index).getEventDate().getTime()); 
			if (diffMiliSecs <= 600000)//600 seconds
				msg10Minutes++;
			else
				break;
		}		
		statistics.add(new StatisticPair("Received Messages in the last 10 minutes", String.valueOf(msg10Minutes)));
		statistics.add(new StatisticPair("Received Messages in the last minute", String.valueOf(msg1Minute)));
		/*
		 * Last received event is the first on the list and vice versa
		 */
		EventDTO first = eventsDTOs.getLast();
		EventDTO last = eventsDTOs.getFirst();
		long timeDiff = last.getEventDate().getTime() - first.getEventDate().getTime();
		timeDiff = timeDiff / 60000;//60 seconds
		if(timeDiff == 0) {
			timeDiff = 1;
		}
		
		statistics.add(new StatisticPair("Average Messages per minute", String.valueOf(EventServiceManager.getInstance().getCountEventDTOs() / timeDiff)));
		return statistics;
	}
}
